<?php
/**
 * Created by PhpStorm.
 * User: shutao
 * Date: 2018/10/26
 * Time: 16:26
 */

namespace wechat\models;

use tt\common\components\TtActiveRecord;
use yii\db\Migration;

/**
 * 小程的 session_key
 * Class WeSessionKey
 * @package wechat\models
 *
 * @property integer $id
 * @property string $code
 * @property string $session_key
 * @property integer $uid
 * @property integer $wuid
 * @property integer $created_at
 */
class WeSessionKey extends TtActiveRecord
{
    public static function tableName()
    {
        return 'we_session_key';
    }

    public function createTableWithName(Migration $migration, $tableName)
    {
        $migration->createTable($tableName, [
            'id' => $migration->primaryKey()->unsigned(),
            'code' => $migration->string(40)->notNull(),
            'openid' => $migration->string(100)->notNull(),
            'session_key' => $migration->string(40)->notNull(),
            'uid' => $migration->integer()->notNull()->unsigned(),
            'wuid' => $migration->integer()->notNull()->unsigned(),
            'created_at' => $migration->integer()->notNull()->defaultValue(0)->unsigned()
        ]);
        $migration->addCommentOnTable($tableName, '小程序 session_key');
        $migration->createIndex('session_key', $tableName, 'session_key');
    }

    public function attributeLabels()
    {
        return [
            'uid' => '用户 id',
            'wuid' => 'WeUser.id'
        ];
    }

    public function beforeSave($insert)
    {
        if (!$this->created_at) {
            $this->created_at = time();
        }
        return parent::beforeSave($insert);
    }

    public function scenarios()
    {
        return [
            self::SCENARIO_DEFAULT => [
                'code', 'session_key', 'uid', 'wuid', 'openid'
            ]
        ];
    }
}